import type { LoginState, LoginSuccessVo, OauthLoginState } from '#/auth/login'
import type { UserState } from './types/user'
import { loginApi } from '@/api/auth'
import type { MemberUserUpdateByLogin} from '#/member/memberUser'
import { getMemberUserLoginInfoApi ,updateByLoginMemberUserApi} from '@/api/member/memberUser'
import { store } from '@/stores'

export const useUserStore = defineStore(`${import.meta.env.VITE_NAMESPACE}-user`, {
  state: (): UserState => ({
    accessToken: '',
    refreshToken: '',
    user: {},
  }),
  actions: {
    /**
     * 获取token
     */
    getAccessToken() {
      return `Bearer ${this.accessToken}`
    },
    /**
     * 获取刷新token
     */
    getRefreshToken() {
      return this.refreshToken
    },
    /**
     * 获取租户id
     */
    getTenantId() {
      return this.user?.tenantId ?? null
    },
    /**
     * 设置登录成功
     * @param data
     */
    async setLoginSuccess(data: LoginSuccessVo) {
      this.accessToken = data.accessToken
      this.refreshToken = data.refreshToken
      await this.setLoginUserInfo()
    },
    /**
     * 获取登录用户信息
     */
    async setLoginUserInfo() {
      const res = await getMemberUserLoginInfoApi()
      this.user = res.data
    },
    /**
     * 更新用户信息
     * @param data
     */
    updateUserInfo(data: MemberUserUpdateByLogin) {
      return new Promise<void>((resolve, reject) => {
        updateByLoginMemberUserApi(data).then(async (res) => {
          if(res.success) {
            await this.setLoginUserInfo()
            resolve()
          }else {
            reject(res.msg)
          }
        }).catch((err) => {
          reject(err)
        })
      })
    },
    /**
     * 登录
     * @param form
     */
    async login(form: LoginState | OauthLoginState) {
      return new Promise<LoginSuccessVo>((resolve, reject) => {
        loginApi(form).then(async (res) => {
          await this.setLoginSuccess(res.data)
          resolve(res.data)
        }).catch((err) => {
          reject(err)
        })
      })
    },
    async handRefreshToken() {

    },
    /**
     * 退出登录
     */
    async logout() {
      this.accessToken = ''
      this.refreshToken = ''
      this.user = {}
    },
  },
  persist: {
    storage: {
      getItem(key: string) {
        return uni.getStorageSync(key)
      },
      setItem(key: string, value: string) {
        uni.setStorageSync(key, value)
      },
    },
  },
})

export function useUserStoreHook() {
  return useUserStore(store)
}
